﻿using Grpc.Core;
using Microsoft.Extensions.Logging;
using SHKF.B2C.Erp.BLL.SugarIOC;
using SHKF.B2C.Erp.BLL.WorkingCenter;
using SHKF.B2C.Erp.Model.Entity;
using SHKF.B2C.SaleServices.Protos;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SHKF.B2C.ErpServices.Services
{
    public class SaleService : GSaleService.GSaleServiceBase
    {
        private readonly ILogger<SaleService> logger;
        private readonly WorkingCenterBLL workingCenterBLL;

        public SaleService(ILogger<SaleService> logger, WorkingCenterBLL workingCenterBLL)
        {
            this.logger = logger;
            this.workingCenterBLL = workingCenterBLL;
        }

        public override Task<OKResponse> Save(SaleRequest request, ServerCallContext context)
        {
            try
            {
                //销售单操作
                this.SaveSaleInfo(request);

                //物流

                //返回结果
                OKResponse oK = new OKResponse();
                oK.Code = 200;
                return Task.FromResult(oK);
            }
            catch (Exception ex)　
            {
                this.logger.LogInformation(ex.InnerException.Message);

                OKResponse oK = new OKResponse();
                oK.Message = ex.InnerException.Message;
                oK.Code = -1;
                return Task.FromResult(oK);
            } 
           
        }

        private List<ProductInfoRelatedEntity> LoadProductVList(SaleRequest request)
        {
            try
            {
                long[] inWhere = new long[request.Detail.Count];
                for (int i = 0; i < request.Detail.Count; i++)
                {
                    inWhere[i] = request.Detail[i].ProductSN; //虚拟产品SN
                }

                List<ProductInfoRelatedEntity> productListAll = this.workingCenterBLL.QueryProductInfoRelated(inWhere);
                return productListAll;
            }
            catch (Exception ex)
            { 
                throw ex;
            }
           
        }

        private void SaveSaleInfo(SaleRequest request)
        {
            this.logger.LogInformation($"order:{request.ID} 接收成功!");

            //1.获取erp映射商店
            int shopVSN = request.ShopSN; //虚拟店SN
            List<ShopRelatedEntity> shopList = this.workingCenterBLL.QueryShopRelated(shopVSN); 
            if (shopList == null)
            {
                this.logger.LogInformation($"order:{request.ID} grpc:shopVSN:{shopVSN}没有配置映射门店信息");
                return;
            }

            List<ProductInfoRelatedEntity> productListAll = LoadProductVList(request);
            if(productListAll == null || productListAll.Count == 0)
            {
                this.logger.LogInformation($"order:{request.ID} grpc:shopVSN:{shopVSN}没有映射任何产品信息");
                return;
            }

            foreach (ShopRelatedEntity shopRelated in shopList) //erp店铺映射列表
            {  
                string WarehousSN = shopRelated.WarehousSN;  //分仓SN
                List<ErpOrderDetail> dataDetailList = new List<ErpOrderDetail>();
                string guid = System.Guid.NewGuid().ToString();

                decimal Total = 0;
                foreach (SaleDetail detail in request.Detail)
                { 
                    long productVSN = detail.ProductSN;

                    //判断虚拟产品在这个店是否有映射
                    ProductInfoRelatedEntity productInfoRelated = productListAll.Find(oo => oo.WarehousSN == shopRelated.WarehousSN
                                                                                            && oo.ProductVSN == productVSN);
                    if (productInfoRelated == null)
                    {
                        this.logger.LogInformation($"grpc:productVSN:{productVSN}没有在WarehousSN:{WarehousSN}中映射erp产品SN");
                        continue;
                    }

                    int productSN = productInfoRelated.ProductSN; //erp产品SN

                    //获取库存数 
                    WareHouseDataEntity data = this.workingCenterBLL.QueryWareHouseData(shopVSN, WarehousSN, productSN);
                    if (data != null)
                    { 
                        int remainder = data.Qty - detail.Qty;
                        if( remainder >= 0) //如果库存足够
                        {
                            ErpOrderDetail orderDetail = new ErpOrderDetail();
                            orderDetail.Guid = System.Guid.NewGuid().ToString();
                            orderDetail.ParentGuid = guid;
                            orderDetail.ProductSN = productSN;
                            orderDetail.OrderQty = detail.Qty;
                            orderDetail.OrderPrice = (decimal)detail.Price;
                            orderDetail.OrderTotal = detail.Qty * (decimal)detail.Price; 

                            dataDetailList.Add(orderDetail); 
                            Total += orderDetail.OrderTotal;

                            //减库存的事放在了clr里统一减掉
                        }
                        else //不够剩余多少循环下一家
                        {
                            detail.Qty -= data.Qty;
                        }
                    }  
                }

                //创建销售单主表数据
                if( dataDetailList.Count > 0)
                { 
                    string serverName = shopRelated.ServerName;  //获取服务器实例
                    SaveFinish(serverName, WarehousSN, guid, Total, request, dataDetailList);
                }
            } 

            //如果产品不够处理

        }

        private void SaveFinish(string serverName, string WarehousSN, string guid, decimal Total, SaleRequest request, List<ErpOrderDetail> dataDetailList)
        {
            try
            {
                this.logger.LogInformation($"order:{request.ID} 保存erp");

                ErpOrderContent orderContent = new ErpOrderContent();
                orderContent.DeliveryAddress = request.DeliveryAddress;
                orderContent.DeliveryName = request.DeliveryName;
                orderContent.DeliveryTel = request.DeliveryTel;
                orderContent.Guid = guid;
                orderContent.WarehousSN = WarehousSN;
                orderContent.PlatformID = request.PlatformID;
                orderContent.Total = Total;
                orderContent.SaleContentSN = request.SN;

                SqlSugarClient db = DbScoped.CreateSugar(serverName);

                db.Insertable<ErpOrderContent>(orderContent)
                    .ExecuteCommand();

                db.Insertable<ErpOrderDetail>(dataDetailList)
                    .UseParameter()
                    .ExecuteCommand();

                this.logger.LogInformation("批量插入明细");

                //执行完成存储过程
                //db.Ado.UseStoredProcedure().GetInt("YZ_Med_LMSystem_S2B2C_CreateSaleContent");
            }
            catch (Exception ex)
            {
                this.logger.LogError($"orderID:{request.ID}" + ex.InnerException.Message);
            }
           
        }
    }
}
